<template>
	<a-card :bordered="false" @scroll='scrollEvent'>
		<div class="table-page-search-wrapper">
			<a-form layout="inline">
				<a-row :gutter="48">

					<a-col :md="8" :sm="24">
						<a-form-item label="产品名称">
							<a-input v-model="queryParam.materialName" placeholder="请输入产品名称" />
						</a-form-item>
					</a-col>

					<a-col :md="8" :sm="24">
						<a-form-item label="料号">
							<a-input v-model="queryParam.materialCode" placeholder="请输入料号" />
						</a-form-item>
					</a-col>

					<a-col :md="!advanced && 8 || 24" :sm="24">
						<span class="table-page-search-submitButtons"
							:style="advanced && { float: 'right', overflow: 'hidden' } || {}">
							<a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
							<!--<a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>-->
						</span>
					</a-col>

					<a-col :md="24" :sm="24" v-if="isFour()">
						<a-form-item label="归属公司：">
							<FCOrgRadioGroup v-model="queryParam.orgIdCompany"
								:filter-types="[$businessEnum.ORG_TYPE_ENUM.COMPANY.id]" />
						</a-form-item>
					</a-col>

					<a-col :md="8" :sm="24" v-if="hasRoleNoAdmin(['general manager', 'caiwu'])">
						<a-form-item label="导出时间">
							<a-range-picker style="width:100%" v-model="queryParam.timeList" format="YYYY-MM-DD" />
						</a-form-item>
					</a-col>

				</a-row>
			</a-form>
		</div>

		<div>
			<span class="table-operator" v-if="isFour()">
				<a-button type="primary" @click="handleToPoolFormBySimpleInStore">录入无单入库池</a-button>
				<a-button type="primary" @click="handleToPoolFormBySimpleOutStore">录入无单出库池</a-button>
				<a-button type="primary" @click="handleToPoolFormByDeliverStore">录入发货池</a-button>
				<a-button type="primary" @click="$refs.addForm.add({ materialType })">新增</a-button>
			</span>
			<span v-if="hasRoleNoAdmin(['general manager', 'caiwu'])">
				<Export text="结存导出" title="结存明细表" url="/emsMaterial/export" :obj="exportParams" />
			</span>
			<span v-if="isHWCGLYROLE()">
				<Export text="结存导出" title="结存明细表" url="/emsMaterial/export" :obj="{
					...exportParams,
					roleType: 2
				}" />
			</span>
			<a-button type="danger" v-if="isProductionDepartment() || managerOrFinance()" @click="$refs.replaceForm.add(3)"
				icon="tool">物料替换</a-button>

			<span v-if="hasBtnPremission(['emsMaterial:hwcExport'])">
				<Export text="导出" title="导出" url="/emsMaterial/hwcExport" :isBody="true" :obj="exportParams" />
			</span>
		</div>


		<s-table ref="table" size="default" :columns="columns" :data="loadData" :alert="true" :scroll="{ x: 1400 }"
			:rowKey="(record) => record.materialId"
			:rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
			<!-- <span slot="image" slot-scope="text, record">
					<image-preview :images="text" />
      </span> -->
			<span slot="image" slot-scope="text,record">
				<image-preview1 :images="text" :imageUrl="record.imageUrl" />
			</span>
			<template slot="inventoryNumber" slot-scope="text, record">
				<span :class="record.inventoryNumber < record.inventoryWarningValue ? 'low-value' : ''">{{ text }}</span>
			</template>

			<span slot="action" slot-scope="text, record">
				<a @click="$refs.editForm.readOnly(record)">详情</a>
				<template v-if="isFour()">
					<div style="display:inline-block">
						<a-divider type="vertical" />
						<a @click="$refs.editForm.edit(record)">编辑</a>
					</div>
				</template>
				<a-divider type="vertical" />
				<a @click="$refs.sendInfoForm.init(record)">发货记录</a>
				<a-divider type="vertical" />
				<a @click="handleDelete(record)">删除</a>
			</span>
		</s-table>

		<a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
			<img style="width: 100%" :src="previewImage" />
		</a-modal>
		<add-form ref="addForm" @ok="handleOk" />
		<edit-form ref="editForm" @ok="handleOk" />
		<preview-form ref="previewForm" />
		<SendInfoForm ref="sendInfoForm" />
		<to-pool-form ref="toPoolForm" @ok="handleOk" />
		<replace-form ref="replaceForm" />
	</a-card>
</template>

<script>
import { STable } from '@/components'
import { del, page } from '@/api/modular/main/emsmaterial/emsMaterialManage'
import addForm from './addForm'
import editForm from './editForm'
import previewForm from './previewForm'  //图片预览
import toPoolForm from './toPoolModal'
import SendInfoForm from './sendInfoForm.vue'
import FCOrgRadioGroup from '@/components/FcOrgRadioGroup/FCOrgRadioGroup'
import replaceForm from '../../emsbom/emsBomReplaceForm.vue'
export default {
	components: {
		STable,
		FCOrgRadioGroup,
		addForm,
		editForm,
		toPoolForm,
		previewForm,
		SendInfoForm,
		replaceForm
	},
	data() {
		return {
			advanced: false, // 高级搜索 展开/关闭
			queryParam: {},  // 查询参数
			// 加载数据方法 必须为 Promise 对象
			loadData: parameter => {
				this.queryParam.materialType = this.materialType
				return page(Object.assign(parameter, this.queryParam)).then((res) => {
					return res.data
				})
			},
			selectedRowKeys: [],
			selectedRows: [],
			defaultExpandedKeys: [],
			replaceFields: {
				key: 'id',
			},
			previewVisible: false,
			previewImage: '',
			viewState: '',
			materialType: this.$businessEnum.MATERIAL_TYPE_ENUM.overseasProduct.id
		}
	},
	computed: {
		exportParams() {
			let obj = {
				materialType: this.materialType,
				...this.queryParam,
				startTime: this.appendTime(this.queryParam.timeList)[0],
				endTime: this.appendTime(this.queryParam.timeList)[1],
			}
			delete obj.timeList
			return obj
		},
		columns() {
			let result
			// 只有总经理和财务能看到价格
			if (this.managerOrFinance()) {
				result = [
					{
						title: '序号', width: '80px',
						align: 'center',
						customRender: (text, record, index) => `${index + 1}`,
					},
					{
						title: '料号',
						dataIndex: 'materialCode'
					},
					{
						title: '产品名称',
						dataIndex: 'materialName'
					},
					{
						title: '规格',
						dataIndex: 'materialModelNumber',
						width: '200px'
					},
					{
						title: '价格',
						dataIndex: 'costPrice',
						width: '100px'
					},
					{
						title: '仓库',
						dataIndex: 'orgIdStorehouseName'
					},
					{
						title: '库位',
						dataIndex: 'orgIdStorehousePositionName'
					},
					{
						title: '图片',
						dataIndex: 'image',
						// customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
						scopedSlots: { customRender: 'image' }
					},
					{
						title: '库存',
						dataIndex: 'inventoryNumber',
						scopedSlots: { customRender: 'inventoryNumber' }
					},
					{
						title: '预警值',
						dataIndex: 'inventoryWarningValue'
					},
					{
						title: '归属公司',
						width: '100px',
						dataIndex: 'orgIdCompanyName',
						ellipsis: false,
					},
					{
						title: '排序',
						dataIndex: 'sort',
						ellipsis: false,
					},
					{
						title: '操作',
						width: '200px',
						dataIndex: 'action',
						fixed: 'right',
						scopedSlots: { customRender: 'action' }
					}
				]
			} else {
				result = [
					{
						title: '序号', width: '80px',
						align: 'center',
						customRender: (text, record, index) => `${index + 1}`,
					},
					{
						title: '料号',
						dataIndex: 'materialCode'
					},
					{
						title: '产品名称',
						dataIndex: 'materialName'
					},
					{
						title: '规格',
						dataIndex: 'materialModelNumber'
					},
					{
						title: '仓库',
						dataIndex: 'orgIdStorehouseName'
					},
					{
						title: '库位',
						dataIndex: 'orgIdStorehousePositionName'
					},
					{
						title: '图片',
						dataIndex: 'image',
						// customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
						scopedSlots: { customRender: 'image' }
					},
					{
						title: '库存',
						dataIndex: 'inventoryNumber',
						scopedSlots: { customRender: 'inventoryNumber' }
					},
					{
						title: '预警值',
						dataIndex: 'inventoryWarningValue'
					},
					{
						title: '归属公司',
						dataIndex: 'orgIdCompanyName',
						ellipsis: false,
					},
					{
						title: '排序',
						dataIndex: 'sort',
						ellipsis: false,
					},
					{
						title: '操作',
						width: '200px',
						dataIndex: 'action',
						fixed: 'right',
						scopedSlots: { customRender: 'action' }
					}
				]
			}
			return result
		}
	},
	methods: {
		//删除
		handleDelete(record) {
			if (record.inventoryNumber != 0) {
				this.$message.error("库存不为0，不能删除");
				return;
			}
			this.$confirm({
				title: '系统提示',
				content: '是否确认删除？',
				onOk: () => {
					del(record).then((res) => {
						if (res.success) {
							this.$message.success('删除成功')
							this.$refs.table.refresh()
						} else {
							this.$message.error('删除失败：' + res.message)
						}
					}).catch((err) => {
						this.$message.error('删除错误：' + err.message)
					})
				},
				onCancel() {
					console.log('Cancel');
				},
			});
		},
		//总经理，以及四个仓库的管理员    返回true
		isFour() {
			return this.hasRole(this.$util.ROLE_ENUM.GENERALMANAGER.id)  //总经理
				|| this.hasRole(this.$util.ROLE_ENUM.MATERIAL_ADMIN3.id)   //线缆
				|| this.hasRole(this.$util.ROLE_ENUM.MATERIAL_ADMIN2.id)   //包材
				|| this.hasRole(this.$util.ROLE_ENUM.MATERIAL_ADMIN1.id)   //原料
				|| this.hasRole(this.$util.ROLE_ENUM.MATERIAL_ADMIN5.id)   //海外仓
		},
		del(record) {
			del(record).then((res) => {
				if (res.success) {
					this.$message.success('删除成功')
					this.$refs.table.refresh()
				} else {
					this.$message.error('删除失败：' + res.message)
				}
			}).catch((err) => {
				this.$message.error('删除错误：' + err.message)
			})
		},
		toggleAdvanced() {
			this.advanced = !this.advanced
		},
		handleOk() {
			this.$refs.table.refresh()
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys
			this.selectedRows = selectedRows
		},
		preview(url) {
			this.previewVisible = true
			this.previewImage = url
		},
		getSuppliers() {
			emsOrgList({ pid: '1473297518794452994', unitRanId: ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id }).then((res) => {
				this.suppliers = res.data
			})
		},
		getOrgs() {
			emsOrgList({ pid: '1473297518794452994', unitRanId: ORG_TYPE_ENUM.COMPANY.id }).then((res) => {
				this.orgs = res.data
			})
		},
		// 录入无单入库池
		handleToPoolFormBySimpleInStore() {
			if (this.selectedRows.length == 0) {
				this.$message.error('请先选择产品')
				return
			}
			this.$refs.toPoolForm.add(this.selectedRows, this.$businessEnum.ORDER_TYPE_ENUM.inOrder.id)
		},
		// 录入无单出库池
		handleToPoolFormBySimpleOutStore() {
			if (this.selectedRows.length == 0) {
				this.$message.error('请先选择产品')
				return
			}
			this.$refs.toPoolForm.add(this.selectedRows, this.$businessEnum.ORDER_TYPE_ENUM.outOrder.id)
		},
		// 录入发货池
		handleToPoolFormByDeliverStore() {
			if (this.selectedRows.length == 0) {
				this.$message.error('请先选择产品')
				return
			}
			this.$refs.toPoolForm.add(this.selectedRows, this.$businessEnum.ORDER_TYPE_ENUM.deliverOrder.id)
		},
		scrollEvent(e) {
			console.log(e)
		}
	}

}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}

.table-image {
	cursor: pointer;
	max-width: 100px;
	max-height: 50px;
	border: solid 1px #cccccc;
}

.low-value {
	color: red;
}
</style>
